package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.mapper.ClassesMapper;
import com.hzit.pojo.Classes;
import com.hzit.pojo.PageResult;
import com.hzit.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService{

    @Resource
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;
    //1. 查询所有学生
    @Override
    public List<Student> findAll() {
        List<Student> students = studentMapper.selectAll();
        for (Student student : students) {
            Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
            student.setCname(classes.getCname());
        }
        return students;
    }

    //2. 分页查询
    @Override
    public PageResult<Student> findByPage(int page, int pageSize) {
        //2.1 开始分页
        PageHelper.startPage(page,pageSize);
        //2.2 查询所有学生
        List<Student> students = findAll();
        //2.3 转换为Page<Student>对象
        Page<Student> studentPage = (Page<Student>) students;
        //2.4 返回
        return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
    }

    //3. 条件查询带分页
    @Override
    public PageResult<Student> search(int page, int pageSize, Student student) {
        //3.1 开始分页
        PageHelper.startPage(page,pageSize);
        //3.2 查询所有学生
        //3.2.1 封装查询实例
        Example example = Example.builder(Student.class).build();
        //3.2.2 得到查询实例中的查询条件对象
        Example.Criteria criteria = example.createCriteria();   //Example.Criteria： 封装一次条件查询过程
        if(student != null){
            if(StrUtil.isNotBlank(student.getSname())){
                criteria.andLike("sname","%" + student.getSname() + "%");
            }
            if(StrUtil.isNotBlank(student.getAddr())){
                criteria.andLike("addr","%" + student.getAddr() + "%");
            }
            if(student.getCid() != null && student.getCid() != 0){
                criteria.andEqualTo("cid",student.getCid());
            }
        }
        //3.2.3 开始查询
        List<Student> students =  studentMapper.selectByExample(example);
        for (Student st : students) {
            Classes classes = classesMapper.selectByPrimaryKey(st.getCid());
            st.setCname(classes.getCname());
        }
        //3.3 转换为Page<Student>对象
        Page<Student> studentPage = (Page<Student>) students;
        //3.4 返回
        return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
    }
}
